<script setup lang="ts">
import {
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElMessageBox,
  FormInstance,
  FormRules,
  ElMessage
} from 'element-plus'

import { useI18n } from '@/hooks/web/useI18n'
import { useCache } from '@/hooks/web/useCache'
import { resetRouter } from '@/router'
import { useRouter } from 'vue-router'
import { loginOutApi, updatePassWord } from '@/api/login'
import { useDesign } from '@/hooks/web/useDesign'
import { getCurUser, getMd5Password, getToken } from '@/utils'
import { ref, reactive, onMounted } from 'vue'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { PATH_URL } from '@/config/axios'
import { getSettings, getPasswordStrength } from '@/api/company'
import boyImg from '@/assets/imgs/boy.png'
import girlImg from '@/assets/imgs/girl.png'
import companyImg from '@/assets/imgs/logo.png'

// const { emitter } = useEmitt()
const tagsViewStore = useTagsViewStore()
const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang
const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('user-info')

const { t } = useI18n()
const logoSrc = ref('')
const { wsCache } = useCache()

const { replace } = useRouter()

// const { proxy } = getCurrentInstance() as any
onMounted(async () => {
  getLogoOrName()
  //获取租户配置
  const setting = await getSettings()
  // console.log('Settings-UserInfo:' + JSON.stringify(setting))
  state.pwLength = setting.pwLength
  state.pwStrength = setting.pwStrength
})
useEmitt({
  //無需填寫按鈕調用方法
  name: 'updateCompanyDataUserInfo',
  callback: () => {
    getLogoOrName()
  }
})
const getLogoOrName = async () => {
  // 獲取當前用戶tenantId

  const user = getCurUser() as any
  const id = user.tenantId

  if (user.userType != 'company') {
    if (user.userType == 'admin' || user.userType == 'staff') {
      if (user.gender == 1) logoSrc.value = boyImg
      else if (user.gender == 0) logoSrc.value = girlImg
    } else {
      logoSrc.value = companyImg
    }

    return
  }

  //公司資料
  if (!id) return

  // if (title.value.length > 12) {
  //   title.value = title.value.slice(0, 12) + '...'
  // }
  try {
    const company = wsCache.get('companyData')
    //await companyDetail({ tenantId: id })
    curUser.fullName = company.data.nameChi
    //'中文名称'
    if (curLang == 'en') curUser.fullName = company.data.nameEng //'英文名称'
    const imgurljson = JSON.parse(company.data.url) //
    let url = PATH_URL + 'form/file/previewFile?isScale=true'
    url += '&fileId=' + imgurljson.fileId
    url += '&time=' + new Date().getTime()
    url += '&token=' + getToken()
    if (company.data.url) logoSrc.value = url
    else logoSrc.value = boyImg
  } catch (error) {
    logoSrc.value = companyImg
  }
}
const loginOut = () => {
  ElMessageBox.confirm(t('common.loginOutMessage'), t('common.reminder'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      const res = await loginOutApi().catch(() => {})
      if (res) {
        let lang = wsCache.get('lang') //不清空多语言
        //let isTimeLogin = wsCache.get('isTimeLogin') //不清空第一次登录状态
        wsCache.clear()
        tagsViewStore.delAllViews()
        wsCache.set('lang', lang)
        // wsCache.set('isTimeLogin', isTimeLogin)
        resetRouter() // 重置静态路由表
        replace('/login')
        // window.location.reload()
      }
    })
    .catch(() => {})
}

// 修改密码
const dialogFormVisible = ref(false)
const curUser = getCurUser() as any
const state = reactive({
  pwLength: 6,
  pwStrength: 3
})
const dialogFormRef = ref<FormInstance>()
const dialogForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const Formrules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: t('login.errPasswordEmpty'), trigger: 'blur' },
    {
      pattern:
        /^[A-Za-z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{3,32}$/,
      message: t('common.errPassportNo'),
      trigger: ['blur', 'change']
    }
  ],
  newPassword: [
    { required: true, message: t('login.errPasswordEmpty'), trigger: 'blur' },
    {
      pattern:
        /^[A-Za-z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{3,32}$/,
      message: t('common.errPassportNo'),
      trigger: ['blur', 'change']
    }
  ],
  confirmPassword: [
    { required: true, message: t('login.errPasswordEmpty'), trigger: 'blur' },
    {
      pattern:
        /^[A-Za-z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{3,32}$/,
      message: t('common.errPassportNo'),
      trigger: ['blur', 'change']
    }
  ]
})

// 打开对话框
const openDialog = () => {
  dialogFormVisible.value = true
  ;(dialogForm.oldPassword = ''), (dialogForm.newPassword = ''), (dialogForm.confirmPassword = '')
}
const changePassword = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let strength = getPasswordStrength(dialogForm.newPassword)
      if (strength < state.pwStrength) {
        ElMessage.warning(t('settings.strengthCheck'))
        return
      }
      if (dialogForm.newPassword != dialogForm.confirmPassword) {
        ElMessage.error(t('common.passwordIsDifferent'))
        return
      }
      const params = {
        oldPassword: getMd5Password(dialogForm.oldPassword),
        newPassword: getMd5Password(dialogForm.newPassword)
      }
      await updatePassWord(params).then((res) => {
        if (res) {
          dialogFormVisible.value = false
        }
      })
    }
  })
}
useEmitt({
  //無需填寫按鈕調用方法
  name: 'updateUserInfo',
  callback: (param) => {
    console.log(param)
  }
})
// 取消
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  dialogFormVisible.value = false
  formEl.resetFields()
}
</script>
<template>
  <ElDropdown :class="prefixCls" trigger="click" style="margin-right: 20px">
    <div class="flex items-center" style="padding-right: 20px; cursor: pointer">
      <el-image
        fit="contain"
        :src="logoSrc"
        alt=""
        style="width: 40px; height: 40px; border-radius: 50%"
      />
      <!-- <img :src="logoSrc" alt="" style="width: 40px; height: 40px; border-radius: 50%" /> -->
      <span class="<lg:hidden text-12px pl-[5px] text-[var(--top-header-text-color)]">{{
        curUser && curUser.fullName ? curUser.fullName : t('common.noName')
      }}</span>
    </div>
    <template #dropdown>
      <ElDropdownMenu>
        <ElDropdownItem @click="openDialog">
          <div>{{ t('common.changePw') }}</div>
        </ElDropdownItem>
        <ElDropdownItem divided @click="loginOut">
          <div class="itemDiv">{{ t('common.loginOut') }}</div>
        </ElDropdownItem>
      </ElDropdownMenu>
    </template>
  </ElDropdown>
  <el-dialog v-model="dialogFormVisible" :title="t('common.changePw')" width="30%" draggable>
    <el-form ref="dialogFormRef" :model="dialogForm" :rules="Formrules">
      <el-form-item :label="t('common.oldPassword')" label-width="120px" prop="oldPassword">
        <el-input
          type="password"
          v-model="dialogForm.oldPassword"
          autocomplete="off"
          :show-password="true"
        />
      </el-form-item>
      <el-form-item :label="t('common.newPassword')" label-width="120px" prop="newPassword">
        <el-input
          type="password"
          v-model="dialogForm.newPassword"
          autocomplete="off"
          :show-password="true"
          :minlength="state.pwLength"
        />
      </el-form-item>
      <el-form-item :label="t('common.confirmPassword')" label-width="120px" prop="confirmPassword">
        <el-input
          type="password"
          v-model="dialogForm.confirmPassword"
          autocomplete="off"
          :show-password="true"
          :minlength="state.pwLength"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="reset(dialogFormRef)">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" @click="changePassword(dialogFormRef)">{{
          t('common.ok')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style scoped>
.el-input {
  width: 300px;
}
</style>
